<?php

namespace app\index\model;

use app\admin\model\Role;
use think\facade\Db;
use think\facade\Session;
use think\Model;

class User extends Model
{
    protected $id;
    // 设置字段信息
    protected $readonly = ['username'];

    public function article()
    {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
    public function comments()
    {
        return $this->hasMany(Comment::class, 'user_id', 'id');
    }
    public function collects()
    {
        return $this->hasMany(Collect::class, 'user_id', 'id');
    }
    public function follows()
    {
        return $this->hasMany(Follow::class, 'follow_user_id', 'id');
    }
    // 个人信息
    public function profile($id)
    {
        $profile =  $this->field('id , username ,nickname ,head_icon , email ,login_time ,signature ,score,role,vip_time')->where('id', $id)->find();
        $isVip = time() > $profile->vip_time ? 0 : 1;
        $role = '';
        if ($profile->role) {
            $role = Role::getRoleName($profile->role);
            if ($role == 'all,') $role = '站长,';
        }
        $user_id = Session::has('user') ? Session::get('user.user_id') : 0;
        $hasFollow = Db::name('follow')->where(['user_id' => $user_id, 'follow_user_id' => $id,'delete_time' => 0])->find();
        $hasFollow = (empty($hasFollow) || $hasFollow['delete_time'] != 0) ? false : true;
        $role = substr($role, 0, strlen($role)) == '' ? '' : substr($role, 0, strlen($role) - 1);
        $data = [
            'profile' => $profile,
            'role' => $role,
            'is_vip' => $isVip,
            'follow' => $hasFollow,
            'articleCount' => $this->find($id)->article()->count(),
            'commentCount' => $this->find($id)->comments()->count(),
            'collectCount' => $this->find($id)->collects()->count(),
            'followCount' => $this->find($id)->follows()->count()
        ];
        return $data;
    }
}
